#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <winsock2.h>
#include "network.h"
#include <easyx.h>
#pragma comment(lib,"ws2_32.lib") // 静态库

char **localIps;
WSADATA wsaData;

bool InitNetwork() {
    // 初始化Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        printf("初始化网络失败,错误码: 0\n");
        return false;
    }
    GetIPs();
    return true;
}

void StopNetwork() {
    FreeIPs();
    WSACleanup();   
}

void GetIPs() {
    struct hostent* phostinfo = gethostbyname("");

    int i = 0;
    while (NULL != phostinfo && NULL != phostinfo->h_addr_list[i]) {
        i++;
    }

    char** ips = (char **)malloc((i + 1) * sizeof(char*)); // 分配存储IP地址的字符串数组
    i = 0;
    while (NULL != phostinfo && NULL != phostinfo->h_addr_list[i]) {
        char* pszAddr = inet_ntoa(*(struct in_addr*)phostinfo->h_addr_list[i]);
        ips[i] = (char*)malloc((strlen(pszAddr) + 1) * sizeof(char)); // 分配每个IP地址的存储空间
        strcpy(ips[i], pszAddr);
        i++;
    }
    ips[i] = NULL; // 最后一个元素为NULL，表示数组的结束
    localIps = ips;
}

void PrintIps(char **ips) {
    while(*ips != NULL) {
        puts(*ips);
        ips++;
    }
}

void FreeIPs() {
    if (localIps == NULL) {
        return;
    }
    int i = 0;
    while (localIps[i] != NULL) {
        free(localIps[i]); // 释放每个IP地址的存储空间
        i++;
    }
    free(localIps); // 释放IP地址数组的存储空间
}

